<?php

namespace App\Admin\Repositories;

use App\Models\WxSetting as Model;
use Dcat\Admin\Repositories\EloquentRepository;

class WxSetting extends EloquentRepository
{
    /**
     * Model.
     *
     * @var string
     */
    protected $eloquentClass = Model::class;



    /*
     * 保存数据或更新数据
     */
    public static function saveConfig($slug, $value = null)
    {
        if ($value == null && is_array($slug)) {
            $cd = new \App\Models\WxSetting();
            foreach ($slug as $k => $v) {
                $where = array('slug' => $k);
                //如果有$value为空,就返回$key的值
                if ($v == null) {
//                    $cd->where($where)->getField('value');
                } else if ($v == "DEL") {
                    //如果$value为DEL,就删除这条记录的值
                    $cd->where($where)->delete();
                } else {
                    //如果$value有正常值，其它操作
                    //如果存在$key,更新
                    if ($cd->where($where)->count() > 0) {
                        $cd->where($where)->update(['value' => $v]);
                    } else {
                        //如果不存在$key，写入一条新数据
                        $cd->insert([
                            'slug' => $k,
                            'value' => $v,
                            'created_at' => date('Y-m-d H:i:s'),
                            'created_at' => date('Y-m-d H:i:s'),
                        ]);
                    }
                }

            }
        } else {
            $cd = new \App\Models\WxSetting();
            $where = array('slug' => $slug);

            //如果有$value为空,就返回$key的值
            if ($value == null) {
                return $cd->where($where)->getField('value');
            } //如果$value为DEL,就删除这条记录的值
            else if ($value == "DEL") {
                return $cd->where($where)->delete();
            } //如果$value有正常值，其它操作
            else {
                //如果存在$key,更新
                if ($cd->where($where)->count() > 0) {

                    return $cd->where($where)->update(['value' => $value]);
                } //如果不存在$key，写入一条新数据
                else {
                    $cd->slug = $slug;
                    $cd->value = $value;
                    return $cd->save();
                }
            }
        }

    }

    /*
     * 通过slug获取配置
     */
    public static function getConfig($slug)
    {
        $WxSettingModel = new \App\Models\WxSetting();
        if (is_array($slug)) {
            $data = $WxSettingModel->whereIn('slug', $slug)->get(['slug', 'value']);
        } else {
            $data = $WxSettingModel->where('slug', $slug)->get(['slug', 'value']);
        }
        $arr = [];
        foreach ($data as $k => $v) {
            $arr[$v['slug']] = $v['value'];
        }
        return $arr;

    }


}
